package org.uim.cricket.analyzer.validate.impl;

import java.util.List;
import java.util.Map;

import org.uim.cricket.analyzer.validate.ValidatableMatch;
import org.uim.cricket.entities.MatchPlayer;
import org.uim.cricket.entities.aggr.SingleInning;
import org.uim.cricket.entities.match.CricketMatch;
import org.uim.cricket.entities.partnerships.FallOfWicket;
import org.uim.cricket.entities.partnerships.Partnership;

public class PartnershipValidator implements ValidatableMatch {

	@Override
	public void processValidation(CricketMatch match, Map<String, List<MatchPlayer>> players) throws Exception {
		if (match == null) return;
		
		for (int i=0; i<match.getInnings().length; i++) {
			SingleInning inn = match.getInnings()[i];
			if (inn == null) continue;
			
			if (inn.getFallWickets() != null) {
				this.validateFallOfWickets(inn, inn.getFallWickets());
			}
			if (inn.getPartnerships() != null) {
				this.validatePShips(inn, inn.getPartnerships());
			}
		}
		
		
	}

	private void validatePShips(SingleInning inn, Partnership[] pships) throws Exception {
		int emptyOvers = 0;
		int total = 0;
		
		for (int i=0; i<pships.length; i++) {
			Partnership  p = pships[i];
			if (p == null) continue;
			
			total++;
			if (p.getBalls() == 0) emptyOvers++;
		}
		
		if (total > emptyOvers) {
			for (int i=0; i<pships.length; i++) {
				Partnership  p = pships[i];
				if (p == null) continue;
				
				if (p.getBalls() > 0) p.setBalls(0);
			}
		}
	}
	
	private void validateFallOfWickets(SingleInning inn, List<FallOfWicket> fows) throws Exception {
		
		for (int i=0; i<fows.size(); i++) {
			FallOfWicket fow = fows.get(i);
			if (fow == null) continue;
			
			if (fow.getOutPlayer() != null || fow.getOutPlayer().getTitleName() == null) {
				throw new Exception ("  Fall of wicket has NULL out player! [" + 
						"Team: " + inn.getBattedTeam() + ", " +
						"Inning: " + inn.getInningMatch() + ", " +
						"Wicket: " + fow.getWicket() + "]");
			}
		}
	}
	
}
